var ProtoCmdID = require("ProtoCmdID");
var MessageManager =
{
    initData:function()
    {
        console.log("messageManager init");
        this.serverIp = "127.0.0.1";
        this.serverPort = "8080";
        this.webSocketPath = "/websocket";
        this.registerPath = "/register";
        this.xhr = new XMLHttpRequest();
        this.ws = null;
        this.eventComponet = null;
    },


    initWebSocket:function(connectCallBack)
    {
        this.ws = new WebSocket("ws://"+this.serverIp+":"+this.serverPort+this.webSocketPath);
        this.ws.onopen = function()
        {
            console.log('---------------open');
            connectCallBack(true);
        };
        this.ws.onmessage = function(evt)
        {
            console.log('---------------onmessage');
            this.messageReceive(evt);
        }.bind(this);
        this.ws.onclose = function(evt)
        {
            console.log('-------------WebSocketClosed!'+evt.data);
            connectCallBack(false);
        };
        this.ws.onerror = function(evt)
        {
            console.log('--------------------WebSocketError!'+evt.data);
            connectCallBack(false);
        };
        this.ws.connectedSever = false;
    },

    setEventComponet:function(eveCom)
    {
        this.eventComponet = eveCom;
    },
    
    register:function(name,pwd,callBack)
    {
        var url = "http://"+this.serverIp+":"+this.serverPort+this.registerPath+"/?usr="+name+"&pwd="+pwd;
        console.log(url);
        this.httpRegister(url,3000,callBack);
    },
    
    login:function(usrID,pwd)
    {
        if(this.ws == null)
        {
            this.initWebSocket(function(conSuc){
                if(conSuc)
                {
                    //connect success
                    console.log("连接成功正在登陆");
                    this.ws.connectedSever = true;
                    this._sendLogin(usrID,pwd);
                }
                else
                {
                    //connect fail
                    console.log("链接服务器失败");
                    this.ws.connectedSever = false;
                }
            }.bind(this));
        }
        else if(this.ws.connectedSever == false)
        {

        }
    },

    _sendLogin:function(usrID,pwd)
    {
        var msg = {
            'cmdID':ProtoCmdID.Login,
            'data':{
                'usrID':usrID,
                'pwd':pwd
            }
        }
        var jsonStr = JSON.stringify(msg);
        this.ws.send(jsonStr);
    },

    enterMineSweep:function()
    {
        var msg = {
            'cmdID':ProtoCmdID.Enter_MineSweep,
        }
        var jsonStr = JSON.stringify(msg);
        this.ws.send(jsonStr);
    },

    sendMessage:function(jsonStr)
    {
        this.ws.send(jsonStr);
    },

    messageReceive:function(evt)
    {
        console.log(evt.data)
        var msgObj = JSON.parse(evt.data);
        var globalEvent = new cc.Event.EventCustom();
        globalEvent.type = msgObj.cmdID;
        globalEvent.msg = msgObj;
        NotificationCenter.dispatchEvent(globalEvent);
    },

    closeWebSocket:function()
    {
      if(this.ws != null)
      {
          this.ws.close();
          this.ws = null;
      }
    },

    httpRegister:function(url,timeout,callback)
    {
        this.xhr.abort();
        var timedout = false;
        var timer = setTimeout(function(){
            timedout = true;
            this.xhr.abort();
            callback("httperror");
        }.bind(this),timeout);
        this.xhr.onreadystatechange = function(){
            if(timedout){ return;}
            clearTimeout(timer);
            if (this.xhr.readyState == 4 && (this.xhr.status >= 200 && this.xhr.status < 400))
            {
                callback(this.xhr.responseText);
            }
        }.bind(this);
        this.xhr.open("GET",url,true);
        this.xhr.send();
    }
};

MessageManager.initData();
module.exports = MessageManager;